package com.anjie.powerproject.controller;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping(value = "file")
public class FileController {

    @GetMapping("/download/{fileName}")
    @ResponseBody
    public ResponseEntity<Object> downloadFile(HttpServletRequest request, @PathVariable String fileName) throws FileNotFoundException {
        String base = ResourceUtils.getURL("classpath:").getPath() + "static/";
        File file = new File(base + fileName);
        if (!file.exists())
        {
            return new ResponseEntity<Object>("{\"code\": \"00002\", \"info\":\"File Not Found!\"}", HttpStatus.BAD_REQUEST);
        }
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        HttpHeaders headers = new HttpHeaders();
        try {
            headers.add ( "Content-Disposition",String.format("attachment;filename=\"%s", URLEncoder.encode(fileName,"UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        headers.add ( "Cache-Control","no-cache,no-store,must-revalidate" );
        headers.add ( "Pragma","no-cache" );
        headers.add ( "Expires","0" );

        ResponseEntity<Object> responseEntity = ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);

        return responseEntity;
    }
}
